package me.muci.B_netty.NIO;

import jdk.Exported;
import org.junit.Before;
import org.junit.Test;

import java.nio.ByteBuffer;
import java.nio.IntBuffer;

/**
 * ClassName: BasicBuffer
 * <p>
 * Description: 举例 Buffer 的使用
 * <p>
 * date: 2021/8/19 11:09
 *
 * @author muci
 * @since JDK 1.8
 */
public class BasicBuffer {
    private ByteBuffer byteBuffer;

    @Before
    public void init(){
        this.byteBuffer = ByteBuffer.allocate(10);
    }

    @Test
    public void testUse() {
        //创建一个大小为10的保存字节的缓冲块
        // 存放数据
        for (int i = 0; i < byteBuffer.capacity(); i++) {
            byteBuffer.put( (byte)i );
        }
        // 读写切换
        byteBuffer.flip();
        // buffer 内维护了两个指针，取值一次，其中一个指针会后移一次，hasRemaining()是判断这两个指针
        while (byteBuffer.hasRemaining()){
            System.out.println((int)byteBuffer.get());
        }
    }

    /**
     * 读取类型顺序
     */
    @Test
    public void testTypePutGet(){
        byteBuffer.putInt(100);
        byteBuffer.putShort((short) 4);
        byteBuffer.putLong((long) 200);
        byteBuffer.putChar('沐');

        byteBuffer.flip();

        //取出类型顺序应该跟存入时顺序保存一次，否则可能会出现异常
        System.out.println(byteBuffer.getInt());
        System.out.println(byteBuffer.getShort());
        System.out.println(byteBuffer.getLong());
        System.out.println(byteBuffer.getChar());

    }

    @Test
    public void testReadOnly(){
        for (int i = 0; i < byteBuffer.capacity(); i++) {
            byteBuffer.put((byte)i);
        }

        byteBuffer.flip();
        //获得只读buffer
        ByteBuffer readOnlyBuffer = byteBuffer.asReadOnlyBuffer();
        System.out.println(readOnlyBuffer.getClass());

        while (readOnlyBuffer.hasRemaining()){
            System.out.println((int)readOnlyBuffer.get());
        }

        //只读buffer保存会保存
        readOnlyBuffer.clear();
        readOnlyBuffer.put("ss".getBytes());

    }
}
